package com.codedef.diaryserver.controller.config;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        // || "".equals(request.getSession().getAttribute("USER_ID")) || "".equals(request.getSession().getAttribute("USER_NAME"))
        if ((uri.startsWith("/diary") || uri.startsWith("/user")) &&
                (request.getSession().getAttribute("USER_ID") == null || request.getSession().getAttribute("USER_NAME") == null)) {
            request.getSession().setAttribute("ERROR_MESSAGE", "请重新登录");
            return false;
        }
        request.getSession().removeAttribute("ERROR_MESSAGE");
        return true;
    }
}
